<?php
/**
 * 材料(大、小)类上传
 * User: bgl
 * Date: 2023/6/20
 * Time: 15:13
 */

namespace App\Admin\Controllers\Products;


use App\Importer\Basics\BImporter;
use App\Models\Product\ProductMaterialClassifyMax;
use App\Models\Product\ProductMaterialClassifyMin;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MaterialClassifyUploadController extends AdminController{

    protected $title = '材料类别上传';

    protected function grid(){
        $type = request('type');
        return view("products.material-classify.upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    /**
     * 材料大类
     */
    private function _importClassifyMax(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];

            $errors = [];
            $count = 1;
            $codeArr = [];
            foreach($data as $row){
                $count++;
                $_titleCn = $row[0] ? trim($row[0]) : '';
                $_code = $row[1] ? trim($row[1]) : '';

                if(!$_titleCn || !$_code){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                $code = strtoupper($_code);
                if (!preg_match("/^[A-Z]{1}$/", $code)) {
                    $errors[$count] = ',材料代码(缩写)不正确';
                    continue;
                }

                if(!in_array($code, $codeArr)){
                    $codeArr[$count] = $code;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }
                $codeCount = ProductMaterialClassifyMax::query()->where('code',$code)->count();
                if($codeCount > 0){
                    $errors[$count] = $code.',系统已存在该材料代码(缩写)';
                    continue;
                }

                DB::beginTransaction();
                $classifyMax = ProductMaterialClassifyMax::query()
                    ->create([
                        'title' => $_titleCn,
                        'code'  => $code
                    ]);
                if(!$classifyMax){
                    DB::rollBack();
                    continue;
                }
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 材料中类
     */
    private function _importClassifyMin(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];

            $errors = [];
            $count = 1;
            $codeArr = [];

            foreach($data as $row){
                $count++;
                $_maxCode = $row[0] ? trim($row[0]) : '';
                $_titleCn = $row[1] ? trim($row[1]) : '';
                $_code = $row[2] ? trim($row[2]) : '';

                if(!$_maxCode || !$_titleCn || !$_code){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                $maxCode = strtoupper($_maxCode);
                if (!preg_match("/^[A-Z]{1}$/", $maxCode)) {
                    $errors[$count] = ',材料大类代码(缩写)不正确';
                    continue;
                }

                $code = strtoupper($_code);
                if (!preg_match("/^[A-Z]{2}$/", $code)) {
                    $errors[$count] = ',材料小类代码(缩写)不正确';
                    continue;
                }

                if(!in_array($code, $codeArr)){
                    $codeArr[$count] = $code;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }

                $classifyMax = ProductMaterialClassifyMax::query()->where('code',$maxCode)->first();
                if(!$classifyMax){
                    $errors[$count] = $maxCode.',系统不存在该材料大类代码(缩写)';
                    continue;
                }

                $reCount = ProductMaterialClassifyMin::query()->where('code',$code)->count();
                if($reCount > 0){
                    $errors[$count] = $code.',系统已存在该材料小类代码(缩写)';
                    continue;
                }

                DB::beginTransaction();
                $classify = ProductMaterialClassifyMin::query()
                    ->create([
                        'parent_id' => $classifyMax->id,
                        'title' => $_titleCn,
                        'code'  => $code,
                    ]);
                if(!$classify){
                    DB::rollBack();
                    continue;
                }
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }


    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
